<?php

namespace app\admin\controller;

use app\admin\model\XPersonalremind;
use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 客户投诉表头
 *
 */
class Complainthead extends Backend
{
    /**
     * Complainthead模型对象
     * @var \app\admin\model\Complainthead
     */
    protected $model = null;
    
    protected $quickSearchField = ['BILLNO'];
    protected $noNeedLogin      = ['*'];

    protected $defaultSortField = 'BILLNO,desc';
    protected $combody=null;
    protected $preExcludeFields = [''];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\Complainthead;
        $this->combody= new \app\admin\model\Complaintbody();
    }
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $sy_type=$this->request->get('code');
        $sy_where='';
        $adminInfo          = $this->auth->getInfo();
        if($sy_type && $sy_type=='TSXX'){
            $sy_where=" complaintbody.zgflag='0' and corplib.COMPANYTYPE='客户' and (corplib.pflag='1' or exists (select * from admin where CHARINDEX(corplib.DEPT,admin.department)>0 and admin.username='$adminInfo[username]'))";
        $res = $this->model

           ->field("complainthead.BILLNO,c.CORPCODE,c.YBH,cc.REMARK as PNAME,c.BILLDT,c.TYPIST,c.TYPISTDT")

            ->join('corplib','complainthead.corpcode=corplib.corp')
            ->join('complaintbody ','complainthead.billno=complaintbody.billno')
            ->where($where)
            ->where($sy_where)
//            ->order($order)
//            ->fetchSql()->select();
//        var_dump($res);die;
            ->paginate($limit);
        }else{
            $res = $this->model
                ->field("complainthead.BILLNO,CORPCODE,YBH,complaintbody.REMARK  as PNAME,BILLDT,TYPIST,TYPISTDT")
                ->join('complaintbody ','complainthead.billno=complaintbody.billno')
//                ->withJoin('getbody', $this->withJoinType)

                ->where($where)
                ->order($order)
//                ->fetchSql()->select();
                ->paginate($limit);
//            var_dump($res);die;
        }
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 添加
     */
    public function add()
    {

        if ($this->request->isPost()) {
            $adminInfo          = $this->auth->getInfo();
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $BILLNO='TS'. $this->microtime_format('YmdHisx',$this->microtime_float());
            $head=[
                'CORPCODE'=>$data['CORPCODE'],
                'BILLNO'=>$BILLNO,
                'BILLDT'=>$data['BILLDT'],
                'YBH'=>$data['YBH'],
                'TYPIST'=>$adminInfo['nickname'],
                'TYPISTDT'=>date('Y-m-d H:i:s',time()),
            ];
            $body=[
                'BILLNO'=>$BILLNO,
                'COMPITEM'=>isset($data['COMPITEM'])?$data['COMPITEM']:'',
                'REMARK'=>isset($data['PNAME'])?$data['PNAME']:'',
                'TYPE'=>isset($data['TYPE'])?$data['TYPE']:'',
                'TSNAME'=>isset($data['TSNAME'])?$data['TSNAME']:'',
                'ZGREMARK'=>isset($data['ZGREMARK'])?$data['ZGREMARK']:'',
                'ZGR'=>isset($data['ZGR'])?$data['ZGR']:'',
                'ZGDATE'=>isset($data['ZGDATE'])?$data['ZGDATE']:'',
                'ZGFLAG'=>isset($data['ZGFLAG'])?$data['ZGFLAG']:'',
                'ZGMANAGER'=>isset($data['ZGMANAGER'])?$data['ZGMANAGER']:'',
                'FILENAME'=>isset($data['FILENAME'])?$data['FILENAME']:'',
                'DEMO'=>isset($data['DEMO'])?$data['DEMO']:''
            ];
            $result = false;
            Db::startTrans();
            try {
                //头入库
                $result = $this->model->save($head);
                //身入库
                $this->combody->save($body);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }
        $this->error(__('Parameter error'));
    }
    /**
     * 编辑
     */
    public function edit()
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model
            ->field("complainthead.BILLNO,CORPCODE,YBH,complaintbody.REMARK as PNAME,BILLDT,TYPIST,TYPISTDT,COMPITEM,TYPE,TSNAME,ZGREMARK,ZGR,ZGDATE,ZGFLAG,ZGMANAGER,FILENAME,DEMO")
            ->join('complaintbody ','complainthead.billno=complaintbody.billno')
            ->where('complainthead.BILLNO',$id)
//            ->fetchSql()
            ->find();
//        var_dump($row);die;
//        $row = $this->model->withJoin('getbody')  ->find($id);

        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            $head=[
                'BILLDT'=>$data['BILLDT'],
                'YBH'=>$data['YBH'],
//                'REMARK'=>$data['REMARK'],
            ];
            $body=[
                'COMPITEM'=>isset($data['COMPITEM'])?$data['COMPITEM']:'',
                'REMARK'=>isset($data['PNAME'])?$data['PNAME']:'',
                'TYPE'=>isset($data['TYPE'])?$data['TYPE']:'',
                'TSNAME'=>isset($data['TSNAME'])?$data['TSNAME']:'',
                'ZGREMARK'=>isset($data['ZGREMARK'])?$data['ZGREMARK']:'',
                'ZGR'=>isset($data['ZGR'])?$data['ZGR']:'',
                'ZGDATE'=>isset($data['ZGDATE'])?$data['ZGDATE']:'',
                'ZGFLAG'=>isset($data['ZGFLAG'])?$data['ZGFLAG']:'',
                'ZGMANAGER'=>isset($data['ZGMANAGER'])?$data['ZGMANAGER']:'',
                'FILENAME'=>isset($data['FILENAME'])?$data['FILENAME']:'',
                'DEMO'=>isset($data['DEMO'])?$data['DEMO']:''
            ];
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {

                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $this->combody->where('BILLNO',$row->BILLNO)->save($body);
                $result = $row->save($head);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $this->success('', [
            'row' => $row
        ]);
    }
}